#include "uart1.h"
#include <stc8h.h>
#include "RTC1.h"
#include "intrins.h"
#include "eeprom.h"
#include <string.h>
#include "timer0.h"
#define CPUIDBASE   0xfde0
#define ID_ADDR     ((unsigned char volatile xdata *)(CPUIDBASE + 0x00))
#define FOSC        22118400UL
#define BRT         (65536 - FOSC / 9600 / 4)	
bit	busy;
char xdata buffer[256];
char rptr=0;
bit rese=0;


char is_equal(char arr[], const char *str) {
    int i = 0;
    while (str[i] != '\0') {
        if (arr[i] != str[i]) return 0; // 字符不同
        i++;
    }
    // 检查数组是否也以'\0'结尾
    return (arr[i] == '\0');
}

void UartSend(char dat){
	while(busy);
	busy=1;
	SBUF=dat;
}
void UartSendStr(char *p){
	while(*p){
		UartSend(*p++);
	}
}
void Uart1_Isr(void) interrupt UART1_VECTOR
{

	if (TI)				//检测串口1发送中断
	{
		TI = 0;			
		busy=0;
	}
	if (RI)				
	{
		RI = 0;	
		RTCIEN = 0x00;                              //关闭RTC秒中断
		showsec(1);
		dpf(3000);
		buffer[rptr++]=SBUF;



		if(rptr>4){
			if(buffer[rptr-1]=='#' && buffer[rptr-2]=='P'&& buffer[rptr-3]=='S'&& buffer[rptr-4]=='I'){
				IAP_CONTR=0X60;
			}
		}
		if(is_equal(buffer,"@STOP")){
			dpf(1000);
		}
		if(rptr>1){
			if(buffer[rptr-1]==0x0a && buffer[rptr-2]==0x0d){
				runcmd();
			}
		}
		if(rptr==11){
			runcmd();
		}
		
	}
}
void printbuff(void){
	UartSendStr(buffer);
}
void processBuffer(void){

}
void Uart1_Init(void)	//115200bps@33.1776MHz
{
	SCON = 0x50;		//8位数据,可变波特率
	AUXR |= 0x40;		//定时器时钟1T模式
	AUXR &= 0xFE;		//串口1选择定时器1为波特率发生器
	TMOD &= 0x0F;		//设置定时器模式
	TL1 = BRT;			//设置定时初始值
	TH1 = BRT >> 8;		//设置定时初始值
	ET1 = 0;			//禁止定时器中断
	TR1 = 1;			//定时器1开始计时
	ES = 1;				//允许串口中断
	EA = 1;				//开放CPU中断
	busy=0;
	rptr=0;
	memset(buffer,0,256);

}

void getID(void){
		char i;
		P_SW2 |= 0x80; 
	    for (i=0; i<7; i++)
    {
        UartSend(ID_ADDR[i]);
    }
}
char putchar(char c){
	UartSend(c);
	return c;
}
void runcmd(){
	if(buffer[0]==0x14){
		INIYEAR=buffer[1];
		INIMONTH=buffer[2];
		INIDAY=buffer[3];
		INIWEEK=buffer[4];
		INISEC=buffer[7];
		INIMIN=buffer[6];
		INIHOUR=buffer[5];
		INISSEC=buffer[rptr-3];
		RTCCFG |= 0x01;     //触发RTC寄存器初始化 +
	}
	showm();
	rptr=0;
	memset(buffer,0,256);

}